<template>
  <div class="basic_table">
    <div class="self_table" ref="wrapRef">
      <div class="table_operation" v-if="selectedAllRowRef.length > 0">
        已选<span>{{ selectedAllRowRef.length }}</span
        >条
      </div>
      <!-- :max-height="tableHeightRef"
      table-layout="auto" -->
      <el-table
        ref="tableElRef"
        v-bind="getBindValue"
        @header-dragend="setHeaderWidth"
        @row-click="customRowClick"
        @sort-change="handleSortChange"
        @selection-change="getRowSelection"
      >
        <!-- 多选 -->
        <el-table-column
          v-if="selection"
          width="48"
          fixed="left"
          align="center"
          type="selection"
          :reserve-selection="reserveSelection"
          :selectable="selectable"
        />
        <template v-for="item in columns">
          <!-- 自定义索引 -->
          <template v-if="item.type === 'index' && !item.displayFlag">
            <el-table-column
              :key="item[item.field]"
              fixed="left"
              align="center"
              v-bind="{ ...getItemBindValue(item) }"
              type="index"
              :index="item.index"
            />
          </template>
          <!-- <template v-else-if="item.children && item.children.length">
          <table-column :key="item[item.field]" :child="item" />
        </template> -->
          <template v-else-if="item.type !== 'index' && !item.displayFlag">
            <el-table-column
              :key="item[item.field]"
              :min-width="item.width ? item.width : '100'"
              v-bind="{ ...getItemBindValue(item) }"
              :prop="item.field"
            >
              <!-- 表头插槽 -->
              <template #header="scope">
                <table-slot v-if="slots[item.field + 'Header']" :slot-name="item.field + 'Header'" :column="item" :index="scope.$index" />
                <el-tooltip v-else :disabled="isShowTooltip" :content="scope.column.label" placement="top">
                  <span class="title_head" ref="tableHeadRefs" @mouseover="renderHeader(scope.$index)">
                    {{ scope.column.label }}
                  </span>
                </el-tooltip>
              </template>

              <!-- 表格内容插槽自定义 -->
              <template v-if="slots[item.field]" #default="scope">
                <template v-if="scope.row[item.field] === null">--</template>
                <table-slot v-else :slot-name="item.field" :row="scope.row" :column="item" :index="scope.$index" />
              </template>
              <template v-else #default="scope">
                {{ scope.row[item.field] || '--' }}
              </template>
            </el-table-column>
          </template>
        </template>
      </el-table>
    </div>
    <div v-if="pagination && pagination.total > 0" class="pagination__wrap">
      <el-pagination
        background
        :style="paginationStyle"
        :page-sizes="store.state.apps.pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        v-bind="getPaginationBindValue"
      />
    </div>
  </div>
</template>

<script setup name="BasicTable">
/* eslint-disable */
import { ElTable } from 'element-plus'
import { computed, useAttrs, ref, unref, getCurrentInstance, provide, useSlots } from 'vue'
import { useTable } from './hooks/useTable'
import { useColumns } from './hooks/useColumns'
import { useRowSelection } from './hooks/useRowSelection'
import { useTableScroll } from './hooks/useTableScroll'
import { deepClone } from 'utils'
import { isObject } from 'utils/validate'
import { useCustomRow } from './hooks/useCustomRow'
import { useSticky } from './hooks/useSticky'
import TableSlot from './components/Slot.vue'
import { useStore } from 'vuex'
const store = useStore()
const props = defineProps({
  // 表头
  columns: {
    type: Array,
    default: () => []
  },
  // 是否多选
  selection: {
    type: Boolean,
    default: false
  },
  pageSizes: {
    type: Array,
    default: () => []
  },
  // 是否展示分页
  pagination: {
    type: [Boolean, Object],
    default: false
  },
  // 仅对 type=selection 的列有效，类型为 Boolean，为 true 则会在数据更新之后保留之前选中的数据（需指定 row-key）
  reserveSelection: {
    type: Boolean,
    default: false
  },
  // 禁用复选框
  selectable: {
    type: Function,
    default: function() {
      return true
    }
  },
  canResize: {
    // 表格自适应高度
    type: Boolean,
    default: true
  },
  // 表格吸顶
  canFixed: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['selection-change', 'row-click', 'sort-chang'])

const attrs = useAttrs()
const slots = useSlots()
const options = ref({})
const _this = getCurrentInstance()
provide('tableRoot', _this)

const tableElRef = ref(null)
const innerPropsRef = ref()

const getProps = computed(() => {
  return { ...props, ...attrs }
})
// 把全选数据 同步到 行点击js中useCustomRow
const setCustData = (rows) => {
  custAllData(rows)
}
// 表格
const { handleSortChange, renderHeader, isShowTooltip } = useTable(getProps, tableElRef, emit, 'basic_table')
// 表格row的多选操作
const { selectedAllRowRef, getRowSelection, getCacheRowkeys } = useRowSelection(getProps, tableElRef, emit, setCustData)
// 表格列的操作 getViewColumns(获取可视的column)
const { getColumnsRef } = useColumns(getProps)
// 表格自适应高度（滚动）
// const { getScrollRef, tableHeightRef, redoHeight } = useTableScroll(getProps, tableElRef, getColumnsRef, selectedAllRowRef)
// 表格当前行操作
const { customRowClick, custAllData, multipleSelection } = useCustomRow(getProps, tableElRef, props.selectable, {
  getCacheRowkeys,
  emit
})

const { clearListener, setFixedStyle, updateFixedRight, headerDragend, setScrollXWidth, clearFixedStyle } = useSticky('basic_table', props.canFixed)

// 绑定的表格配置参数
const getBindValue = computed(() => {
  // 重新获取传参数的修改（重新处理）
  let propsData = {
    ...attrs,
    ...unref(getProps)
    // scroll: unref(getScrollRef) // 自适应高度
  }
  options.value = propsData
  return propsData
})
// 绑定的表格列配置参数
function getItemBindValue(item) {
  const delArr = []
  const obj = deepClone(item)
  for (const key in obj) {
    if (delArr.indexOf(key) !== -1) {
      delete obj[key]
    }
  }
  return obj
}
// 绑定的表格分页配置参数
const getPaginationBindValue = computed(() => {
  const PaginationBindValue = props.pagination && isObject(props.pagination) ? { ...props.pagination } : {}
  return PaginationBindValue
})
// 绑定的表格分页样式
const paginationStyle = computed(() => {
  return {
    textAlign: (props.pagination && props.pagination.position) || 'center'
  }
})
// // 表头拖拽宽度计算
function setHeaderWidth(nw, ow, col) {
  // 拖拽最小宽度问题
  const widthTable = parseInt(document.querySelector('.basic_table .el-table').offsetWidth)
  let realWidth = parseInt((col.minWidth * widthTable) / 100)
  if (nw > realWidth + 50) {
    col.width = realWidth + 50
  }
  //  else if (nw < ow) {
  //   // 拖拽不能小于默认的最小宽度
  //   col.width = ow
  // } else {
  //   col.width = nw
  // }
  // col.minWidth = col.width

  //左拖拽bug
  else {
    col.width = nw < col.minWidth ? col.minWidth : nw
  }
  headerDragend()
}

function setProps(props) {
  innerPropsRef.value = { ...unref(innerPropsRef), ...props }
}
function resetTableSelect() {
  selectedAllRowRef.value = []
  multipleSelection.value = []
  tableElRef.value.clearSelection()
}
// // 表格事件
const tableAction = {
  // redoHeight, // 表格自适应高度
  setProps,
  getRowSelection,
  emit,
  resetTableSelect
}
const key = Symbol('basic-table')
provide(key, tableAction)
defineExpose(tableAction)
</script>

<style lang="scss" scoped>
.basic_table {
  margin-top: 8px;
  :deep(.el-table td.el-table__cell) {
    border-right: none !important;
  }
  :deep(.el-table th.el-table__cell > .cell) {
    height: 23px;
  }
}
.title_head {
  // display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.table_operation {
  margin: 12px 0;
  color: #666666;
  font-size: var(--el-menu-item-font-size);
  span {
    color: var(--el-color-primary);
    margin: 0 2px;
  }
}
.pagination__wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  // min-height: 36px;
  // position: relative;
  // left: 0;
  // bottom: 0;
  margin-top: 16px;
  .el-pagination {
    padding: 0 15px;
  }
}
.pagination__wrap.fixed-footer {
  position: fixed;
  bottom: 0;
  // background: rgba(75, 75, 75, 0.85);
  background: #fff;
  z-index: 9999;
}
</style>
